import React, { useEffect, useState,useReducer } from "react";
import {useNavigate,useLocation } from "react-router-dom";
import { Form } from "antd";
import axios from "axios";
import CancelModel from "../../../common/CancelModel";
import getFields from "./getFields.js";
import FormEdit from "../../../common/FormEdit";


import "./index.css";
const initialState = {
  cancelModelStatus: false,
  };
const reducer = (state, action) => {
  console.log("模态框传入",action);
    switch (action.type) {
      case 'changeCancelModel':
          return {
            ...state,
            cancelModelStatus: action.status,
           
          };
          default:
    }
  };

export default function PoiManageList() {
    let location=useLocation();
   /**
  * 设置取消按钮的模态框
  */
  const [store, dispatch] = useReducer(reducer, initialState);
  let navigation=useNavigate();
  const [form] = Form.useForm();
  const{state}=location;
  const[cuiData,setCuiData]=useState();
  /**
   * 处理做法组 加料组数据 
   */
  const[cuiMetData,setCuiMetData]=useState();
  const[cuiAccData,setCuiAccData]=useState();
  console.log("做法组数据",cuiMetData)
  useEffect(()=>{
    if(cuiData && cuiData.methodGroups.length>0){
     let method=cuiData.methodGroups.map((item,index)=>{
        let obj={
          fieldKey: index,
          isListField: true,
          key: index,
          name: item.name,
          options: item.options.map((item,index)=>{
            return {
              fieldKey: index,
              isListField: true,
              key: index,
              name: item.name,
            }
            
          })
        }
        return obj;
      })
      setCuiMetData(method);
    }

    if(cuiData && cuiData.accessoryGroups.length>0){
      let acc=cuiData.accessoryGroups[0].options.map((item,index)=>{
         let obj={
           fieldKey: index,
           isListField: true,
           key: index,
           name: item.name,
           unitPrice: item.unitPrice,
           unitOfMeasure: item.unitOfMeasure,
         }
         return obj;
       })
       setCuiAccData(acc);
     }
   
  },[cuiData])
  /**
 * 刷新表单
 */
useEffect(()=>{
  form.resetFields();
},[cuiMetData,cuiAccData])
  

  /**
   * 查询菜品详情
   */
   function queryCui(id){
    axios({
      headers: {
        'tenantId':500,
        "userId":11111
    },
      method: 'get',
      url:`http://localhost:9101/product/${id}`,
    }).then((data)=>{
    //  setData(data.data);
    console.log("查询data",data)
 
    setCuiData(data.data);
      return true;
       }).catch((data)=>{
        console.log("错误信息",data); 
       })
}


  /**
   * 编辑的数据保存给后端服务器
   * @returns 
   */
   function saveCui(values,id,version){
    axios({
      headers: {
        'tenantId':500,
        "userId":11111
    },
      method: 'put',
      url:`http://localhost:9101/product/${id}`,
      data:{
      ...values,
      version:version
      }
    }).then((data)=>{
      setCuiData(data.data);
      return true;
       }).catch((data)=>{
        console.log("错误信息",data); 
       })
}
      useEffect(()=>{
      queryCui(state.id);
      },[state.id])

  /**
   * 处理编辑菜品 请求体
   */
  function jsonRequest(values){
    /**
     * 处理加料组数据
     */
     let options=[];
     let obj=[{}];
    if(values.accessoryGroups){
       options=values.accessoryGroups.map((item)=>{
        return {
         name: item.name, unitPrice: item.unitPrice, unitOfMeasure: item.unitOfMeasure
        }
      })
      obj=[{
       name:"加菜",
       options: options,
      }]
    }
  /**
   * 处理方法组数据
   */
   let methodObj=[{}];
  if(values.methodGroups){
     methodObj=values.methodGroups.map((item)=>{
      let options=item.options.map((item)=>{
        return{
          name: item.name
        }
      });
      return {
        name:item.name,
        options:options,
      };
    });

  }
  if(values.accessoryGroups && values.accessoryGroups.length>0)
  {
    values.accessoryGroups=obj;
  }
  if(values.methodGroups && values.methodGroups.length>0)
  {
    values.methodGroups=methodObj;
  }
  return values;

  }

  const onFinish = (values) => {
    saveCui(jsonRequest(values),state.id,cuiData.version);
  };


  return (
    <div>
      <FormEdit
        form={form}
        onFinish={onFinish}
        initialValues={{
        name:state.name,
         unitPrice:state.unitPrice,
         unitOfMeasure:state.unitOfMeasure,
         minSalesQuantity:state.minSalesQuantity,
         increaseSalesQuantity:state.increaseSalesQuantity,
         description:state.description,
         methodGroups:cuiMetData,
         accessoryGroups: cuiAccData,
        }}
        name="编辑菜品页面"
        getFields={getFields()}
        resetFields={() => {
          dispatch({type:'changeCancelModel', status:true});
        }}
        saveBack={() => {
          form.submit((e)=>{
            saveCui(jsonRequest(e),state.id,cuiData.version);
          });
          navigation('/cui-manage/cuiList');
        }}
      />
      <CancelModel store={store} dispatch={dispatch} path="/cui-manage/cuiList"/>
    </div>
  );
}
